/*
 * Created by SharpDevelop.
 * User: fatman
 * Date: 10/27/2008
 * Time: 3:40 AM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using ST = System.Threading;

namespace CUALib
{
	/// <summary>
	/// Description of Button.
	/// </summary>
	public enum ButtonStates
	{
		Normal,
		Pressed

	}

	public delegate void ButtonOnClick(object sender, System.EventArgs e);

	public class Button : PanelBase
	{




		public event ButtonOnClick OnClick;

		public void Click()
		{


			/*oldText = this.Text;
			//Console.WriteLine(oldText);
			this.Text = "XX";
			this.Redraw();
			*/

			oldDecorationSet = this.DecorationSet;
			this.DecorationSet = _decorationSetPress;
			Redraw();

			ButtonOnClick boc = OnClick;
			if (boc != null)
			{
				boc(this, new EventArgs());
			}
		}



		ST.TimerCallback tc = null;
		ST.Timer t = null;

		private volatile bool tRunning = false;
		//private volatile string oldText = string.Empty;
		private volatile BoxDrawingDecorationSet oldDecorationSet = null;
		private volatile int tAdd = 0;

		public void tCallBack(Object stateInfo)
		{
			if (tAdd > 0)
			{
				t.Change(50, tAdd);
				tAdd = 0;
				return;
			}
			tRunning = false;
			t.Dispose();
			tAdd = 0;

			//this.Text = oldText;
			if (this.DecorationSet == _decorationSetPress)
			{
				this.DecorationSet = oldDecorationSet;
			}
			Redraw();

		}

		private void Press()
		{
			if (tRunning)
			{
				tAdd = 100;
				Redraw();
			}
			else
			{

				tAdd = 0;
				tc = new ST.TimerCallback(this.tCallBack);
				if (t != null)
					t.Dispose();

				Click();
				t = new ST.Timer(tc);
				tRunning = true;
				t.Change(300, 10);
			}
		}

		public override bool ReceiveEvent(ConsoleKeyInfo cki)
		{
			if (base.ReceiveEvent(cki))
			{
				switch (cki.Key)
				{
					case ConsoleKey.Enter:
						Press();
						break;
					case ConsoleKey.Spacebar:
						Press();
						break;
				}
			}

			return Focused;
		}



		private BoxDrawingDecorationSet _decorationSetFocus = new BoxDrawingDecorationSetAlternate();
		private BoxDrawingDecorationSet _decorationSetUnfocus = new BoxDrawingDecorationSetFarManager();
		private BoxDrawingDecorationSet _decorationSetPress = new BoxDrawingDecorationSetAlternate2();


		public Button(bool consoleExists)
			: base(consoleExists)
		{

		}



		public override BoxDrawingDecorationSet DecorationSet
		{
			get { return base.DecorationSet; }
			set
			{
				base.DecorationSet = value;

			}
		}



		public override bool Focused
		{
			get { return base.Focused; }
			set
			{
				base.Focused = value;
				if (base.Focused)
				{
					this.DecorationSet = _decorationSetFocus;
				}
				else
				{
					this.DecorationSet = _decorationSetUnfocus;
				}

			}
		}







	}
}
